#include "main.h"
/**
*		@brief:	Init module PIT 
*/
void PIT_InitTimer(void){
	SIM->SCGC6 |= SIM_SCGC6_PIT_MASK;		/*Enable clock PIT module*/
	PIT->MCR &= ~(PIT_MCR_MDIS_MASK|		/*Enable module PIT*/
								PIT_MCR_FRZ_MASK);		/*Config timer run to debug mode*/
}
/**
*	@brief Config value to Timer Load Value Register
*	@param Timer: Index Timer such as TIMER0,TIMER1,...
*	@param Value:unit ms
*/
void PIT_ConfigValue(Timer_TypeDef Timer, uint16_t Value){
	PIT->CHANNEL[Timer].LDVAL = Value*(SystemCoreClock/2/1000)-1;	/*Timer load value*/
}

/**
*
*/
void PIT_EnableIRQ(Timer_TypeDef Timer, Mode_TypeDef Mode){
	PIT->CHANNEL[Timer].TCTRL	|= PIT_TCTRL_TIE_MASK|		/*Enable timer interrupt*/
															 PIT_TCTRL_TEN_MASK;		/*Enable timer*/
	if(Mode==MODE_CHAIN){
		PIT->CHANNEL[Timer].TCTRL |= PIT_TCTRL_CHN_MASK;	/*Enable chain mode*/
	}
	NVIC_SetPriority(PIT_IRQn, 1);
	NVIC_EnableIRQ(PIT_IRQn);
}
/**
*
*/
uint8_t PIT_GetFlag(Timer_TypeDef Timer){
	if((PIT->CHANNEL[Timer].TFLG & PIT_TFLG_TIF_MASK)==PIT_TFLG_TIF_MASK){	/*Check Flag set to 1?*/
		return 1;
	}
	else{
		return 0;
	}
}

/**
*
*/
void PIT_ClearFlag(Timer_TypeDef Timer){
	PIT->CHANNEL[Timer].TFLG |= PIT_TFLG_TIF_MASK;	/*write 1 to flag clears it*/
}

/*******************TPM module*************************************************************************************/
void TPM0_Init(void){
	SIM->SCGC6 |= SIM_SCGC6_TPM0_MASK;		/*Enable clock gate for TPM0 module*/
	SIM->SOPT2 |= SIM_SOPT2_TPMSRC(1)|
								SIM_SOPT2_PLLFLLSEL_MASK;		/*Select MCGPLLCLK/2 =48Mhz source for the TPM counter clock*/
		
	TPM0->SC |= TPM_SC_CMOD(1);						/*Config TPM counter increments on every TPM counter clock*/
	TPM0->SC |= TPM_SC_PS(0);							/*Prescale=CMOD/1=48Mhz*/
}

/**
*	@brief Function config duty pulse: Duty() = (CnV*256)/(MOD+1)
*	
*/
void TPM0_EPWMDuty(Channel_TypeDef Channel,uint8_t Duty){
	TPM0->CNT = 0;
	TPM0->MOD = 0xFFFF;
	TPM0->CONTROLS[Channel].CnV = Duty*((uint32_t)(TPM0->MOD + 1)/256);
	
	/*Config TPM mode EPWM- MSB=1, MSA=0, ELSB=1, ELSA=0*/
	TPM0->CONTROLS[Channel].CnSC |= TPM_CnSC_MSB_MASK;
	TPM0->CONTROLS[Channel].CnSC &= ~TPM_CnSC_MSA_MASK;
	TPM0->CONTROLS[Channel].CnSC |= TPM_CnSC_ELSB_MASK;
	TPM0->CONTROLS[Channel].CnSC &= ~TPM_CnSC_ELSA_MASK;	
}
